package cn.itcast.com.network.udp.v2;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class Receiver {
    public static void main(String[] args) throws IOException {
        boolean flag = true;
        //创建socket对象
        DatagramSocket datagramSocket = new DatagramSocket(8282);
        //创建用于接收数据的数据报包，通过socket对象的receive方法进行接受
        byte[] buff = new byte[1024];
        DatagramPacket datagramPacket = new DatagramPacket(buff,0,buff.length);
        //接收端获得键盘输入的数据发送给发送端
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        while (flag){
            //使用receive将接受的数据传入缓冲数组
            datagramSocket.receive(datagramPacket);
            //获得数据
            String receiveData = parseData(datagramPacket);
            //发送数据
            senData(datagramSocket,datagramPacket,bufferedReader);

            if(receiveData.equals("886")){
                break;
            }
        }

        //释放资源
        datagramSocket.close();

    }

    //发送数据
    private static void senData(DatagramSocket datagramSocket,DatagramPacket datagramPacket, BufferedReader bufferedReader) throws IOException {
        //获得字符串
        String s = bufferedReader.readLine();
        byte[] bytes = s.getBytes();
        DatagramPacket datagramPacket1 = new DatagramPacket(bytes, 0, bytes.length, datagramPacket.getAddress(), datagramPacket.getPort());
        datagramSocket.send(datagramPacket1);
    }
    //返回值用来判断是否为886从而中断进程
    private static String parseData(DatagramPacket datagramPacket) {
        //输出数组
        //获得字节数组数据
        byte[] data = datagramPacket.getData();
        //获得偏移量
        int offset = datagramPacket.getOffset();
        //获得字节个数
        int length = datagramPacket.getLength();
        //通过解析获得文字
        String s = new String(data,offset,length);
        //获得发送方的ip地址
        InetAddress address = datagramPacket.getAddress();
        //获得发送方的端口号
        int port = datagramPacket.getPort();
        System.out.println("接受来自 "+address+":"+port+"  "+s);
        return s;
    }
}
